<template>
  <div class="container">
    <!-- 新增学科的dialog -->
    <el-dialog
      :title="showTitle"
      :visible="dialogVisible"
      width="30%"
      @close="closeDialog"
      @closed="$refs.addRef.resetFields()"
    >
      <el-form
        ref="addRef"
        :model="addForm"
        label-width="100px"
        :rules="addRules"
      >
        <el-form-item label="学科名称" prop="subjectName">
          <el-input style="width: 300px" v-model="addForm.subjectName" />
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch
            v-model="addForm.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ccc"
            active-value="1"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="addSubject">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/subjects.js'
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    addForm: {
      type: Object,
      required: true
    }
  },

  data () {
    return {
      // 新增表单
      addRules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ]
      }
    }
  },

  computed: {
    showTitle () {
      if (this.addForm.id) {
        return '修改学科'
      } else {
        return '新增学科'
      }
    }
  },

  methods: {
    closeDialog () {
      this.$emit('closeDialog')
    },

    // 新增学科确定按钮 + 修改确定按钮
    addSubject () {
      this.$refs.addRef.validate(async (flag) => {
        if (!flag) return
        if (this.addForm.id) {
          await update(this.addForm)
          this.closeDialog()
          this.$message.success('修改学科成功')
        } else {
          await add(this.addForm)
          /// console.log(res)
          this.closeDialog()
          this.$message.success('新增学科成功')
        }
        this.$emit('getSubjectsList')
      })
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep {
  .el-dialog__footer {
    text-align: right;
  }
}
</style>
